package com.gxa.insurance.intercepter;


import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.util.StringUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

/**
 * @author Min
 *  设计一个拦截器，用于校验前端是否携带token 并校验
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    /**
     * 拦截前处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o 封装的一个方法的Method对象 ：/user/login -> login() ->反射得到方法信息->注解
     *          例如：设计一个自定义注解：@NeedToken
     * @return true 放行  false拦截不放行
     * @throws Exception  把所有异常整合为一个，应为有ExceptionController存在
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//        if(!(o instanceof HandlerMethod)) {
//            return true;
//
//        }
//             // 获取前端的token
//             String token = httpServletRequest.getHeader("token");
//             // 服务器中存的token
//             HttpSession session = httpServletRequest.getSession();
//             Object sysToken = session.getAttribute("token");
//             if(StringUtil.isEmpty(token)){
//                throw  new BusinessException(ExceptionCode.EMPTY_TOKEN);
//             }else if(!token.equals(sysToken)){
//                throw new BusinessException(ExceptionCode.WRONG_TOKEN);
//             }
           return true;
    }

    /**
     * 控制器执行后的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 请求执行后的处理
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
